/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package server.server;

import server.closeClientConnections.CloseClientConnectionsProducer;
import server.server.senderEvent.SenderProducer;
import server.serverDB.ServerDB;
import java.io.IOException;
import java.net.ServerSocket;

/**
 *
 * @author Александр Емельянов (mr.lex91@gmail.com)
 */
class AcceptionHandler extends Thread{
    private boolean isRun=false;
    private ServerSocket server;
    private CloseClientConnectionsProducer evConnectionsProd;//=new CloseClientConnectionsProducer();
    private SenderProducer evSendProd= new SenderProducer();
    private ServerDB dataBase;
    private Object sync=new Object();

    AcceptionHandler(ServerSocket server, ServerDB dataBase)
    {
        this.server=server;
        this.dataBase=dataBase;
        evConnectionsProd=new CloseClientConnectionsProducer();
    }
    public void Start()
    {
        synchronized(sync)
        {
            if(!isRun)
            {
                setDaemon(true);
                setPriority(NORM_PRIORITY);
                start();
                isRun=true;
            }
        }
    }
    public void Stop()
    {
        synchronized(sync)
        {
            isRun=false;
        }
    }
    private boolean isRunnable()
    {
        synchronized(sync)
        {
            return isRun;
        }
    }
    @Override
    public void run() {
        while(true)
        {
            try {
                new ClientHandler(server.accept(), evConnectionsProd, evSendProd, dataBase).Start();
            }
            catch (IOException ex) {
            }
            if (!isRunnable()){
                evConnectionsProd.CloseClientConnections();
                return;
            }
        }
    }

}
